
/**
* 对 数据对象进行字段排序
*/
function sortKeys(key, value) {
//  console.log(`key=${key}, value typeof= ${typeof value}`);
  if (value !== null && Array.isArray(value)) {
      return value;
  } else if (value !== null && typeof value === "object") {
    return Object.keys(value).sort()
      .reduce((obj, key) => ({ ...obj, [key]: value[key] }), {});
  }
  return value;
}

/**
* 对 字符串进行sha-256加密
*/
async function sha256Hex(text) {
  let h = await window.crypto.subtle.digest('SHA-256', new TextEncoder('utf-8').encode(text));
  const view = new DataView(h);
  const hexes = [];

    for (let i = 0; i < view.byteLength; i += 4){
      hexes.push(('00000000' + view.getUint32(i).toString(16)).slice(-8));
    }
    return hexes.join('');
}

/**
 * 根据 当前时间戳+data 生成sign值
 * @param data 提交的数据
 * @param timestamp 当前时间戳，必须由调用者传入
 * @param appSecret
 * @returns {Promise<string>}
 */
export async function  getSign(data,timestamp,appSecret = '') {
    let tokenArr = [`appSecret=${appSecret}`]
    data.timestamp = timestamp;
    Object.keys(data).sort().forEach(e => {
      let v= (typeof data[e] === "object")?JSON.stringify(data[e],sortKeys):data[e];
      tokenArr.push(`${e}=${v}`);
  })

  const str = tokenArr.join('&');
  console.log("jsonStr = "+str);

  return await sha256Hex(str);
}


//示例
const form = {
  "title":"西游记",
  "price": 25.90.toFixed(2),
  "barcode":"6043f2a6ae67",
  "saleStores":[
    {"storeName":"新华书店","city":"上海"},
    {"storeName":"三味书屋","city":"北京"}
  ]
};


getSign(form, Date.now(),'hello')
    .then(v => {
      console.log(">>> generate sign = "+v);
    });
